package com.easy.auth.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.easy.auth.domain.FileComparator;
import com.easy.auth.domain.ErrorLog;
import com.easy.auth.service.ErrorLogService;
import com.easy.base.service.impl.EManagerImpl;
import com.easy.common.jdbc.DymaticCondition;
import com.easy.common.jdbc.PageInfo;
import com.easy.common.util.BeanUtil;
import com.easy.common.util.DateUtil;
import com.easy.common.util.FileUtil;
import com.easy.common.util.Parameter;
import com.easy.common.util.SqlUtil;
import com.easy.common.web.PagedList;

@Transactional
@Service
public class ErrorLogServiceImpl extends EManagerImpl<ErrorLog> implements ErrorLogService {

	@Override
	public int removeErrorLog(String oids) {
		int count = 0;
		String[] userIds = oids.split("-");
		String sql = "DELETE FROM ErrorLog_role WHERE userid = ?";
		if (userIds != null) {
			for (String userid : userIds) {
				super.update(sql, userid);
				ErrorLog ErrorLog = new ErrorLog();
				ErrorLog.setOid(userid);
				count += super.remove(ErrorLog);
			}
		}
		return count;
	}

	@Override
	public ErrorLog findErrorLog(ErrorLog ErrorLog) {
		return super.find(ErrorLog);
	}

	@Override
	public PagedList<ErrorLog> findAllErrorLogLike(ErrorLog ErrorLog,
			PageInfo pageInfo) {
		return super.findAllLike(ErrorLog, pageInfo);
	}
	
	@Override
	public List<ErrorLog> getSonErrorLogTree(String id) {
//		String sql="SELECT * FROM ErrorLog WHERE 1=1  AND id_path LIKE '%,"+id+"' AND isfile != true";
//		List<ErrorLog> father= queryList(sql, null,new BeanPropertyRowMapper<ErrorLog>(ErrorLog.class)	);
		String sql="SELECT * FROM ErrorLog WHERE 1=1  AND id_path LIKE '%,"+id+",%'  AND  isfile != 'true'";
		List<ErrorLog> son= queryList(sql, null,new BeanPropertyRowMapper<ErrorLog>(ErrorLog.class)	);
//		father.addAll(son);
		return son;
	}
	public List<ErrorLog> getSonErrorLog(String pid) {
		String sql="SELECT * FROM ErrorLog WHERE  pid = '"+pid+"' AND isfile != 'true'";
		List<ErrorLog> ErrorLogList= queryList(sql, null,new BeanPropertyRowMapper<ErrorLog>(ErrorLog.class)	);
		return ErrorLogList;
	}	
	
	@Override
	public PagedList<ErrorLog> findAllErrorLogEqual(ErrorLog ErrorLog,
			PageInfo pageInfo) {
		return super.findAllEqual(ErrorLog, pageInfo);
	}
	
	
	@Override
	public PagedList<ErrorLog> findAllErrorLogLikeAndEqualPid(ErrorLog ErrorLog,PageInfo pageInfo) {
		String equal= " = ";
		if(ErrorLog.getPid().equals("0")){
			equal= " <> ";
		}
		String r ="pid "+equal+" '"+ErrorLog.getPid()+"'";
		String sql=SqlUtil.getSelectAllLikeValueSql(ErrorLog).replace("pid LIKE '%"+ErrorLog.getPid()+"%'",r );
		return query(sql, null,
				new BeanPropertyRowMapper<ErrorLog>(BeanUtil.getGenericType(this, 0)),
				pageInfo);
	}
	
	
	
	@Override
	public int saveOrEditErrorLog(ErrorLog ErrorLog) {
		return super.saveOrEdit(ErrorLog);
	}

	public PagedList<ErrorLog> getDepHaveUsersByUserid(String depid,
			PageInfo pageInfo) {
		String sql = "SELECT user.* FROM ErrorLog user, ErrorLog_department userdept "
				+ "WHERE 1=1 and user.oid = userdept.userid ";
		DymaticCondition dymaticCondition = new DymaticCondition();
		dymaticCondition.addCondition("AND userdept.departmentid = '?'", depid);

		return super.query(
				sql,
				dymaticCondition,
				new BeanPropertyRowMapper<ErrorLog>(BeanUtil.getGenericType(this, 0)), pageInfo);
	}

	public PagedList<ErrorLog> getDepNotHaveUsersByUserId(String depid,
			PageInfo pageInfo) {
		String sql = "SELECT * FROM ErrorLog WHERE 1= 1 ";
		DymaticCondition dymaticCondition = new DymaticCondition();
		dymaticCondition
				.addCondition(
						"AND oid NOT IN(SELECT user.oid FROM ErrorLog user, ErrorLog_department userDept WHERE userDept.userid = user.oid and userDept.departmentid = '?')",
						depid);

		return super.query(
				sql,
				dymaticCondition,
				new BeanPropertyRowMapper<ErrorLog>(BeanUtil.getGenericType(this, 0)), pageInfo);
	}
	@Override
	public int removeAllErrorLogs() {
		String sql = "DELETE FROM ErrorLog";
		super.update(sql);
		return 0;
	}


	@Override
	public List<ErrorLog> findAllErrorLogs() {
		String sql="SELECT * FROM ErrorLog WHERE isfile != 'true'";
		List<ErrorLog> ErrorLogList= queryList(sql, null,new BeanPropertyRowMapper<ErrorLog>(ErrorLog.class)	);
		return ErrorLogList;
	}
	
//	@Override
	public List<ErrorLog> findAllList() {
		return super.findList(new ErrorLog());
	}
	
	
	@Override
	public int  readNewFloderAndErrorLog(String maxid){
		//List<ErrorLog> ErrorLogList=findAllList();
		 List<String> newDirectory=compartDataAndDirectory(Parameter.PID,Parameter.FILE_PATH);
		
		return 0;
	}
	/**
	 * 废弃
	 * @param pid
	 * @param filePath
	 * @return
	 */
	
	public List<String>  compartDataAndDirectory(String pid,String filePath){
		List<String> newDirectory=new LinkedList<String>();
		List<ErrorLog> ErrorLogList=getSonErrorLog(pid);
		File file = new File(filePath);
		File[] fileList = listFilesFilter(file);
		if( fileList.length==ErrorLogList.size()){
			for (int j = 0; j < ErrorLogList.size(); j++) {
				compartDataAndDirectory(ErrorLogList.get(j).getId(),fileList[j].getPath());
			}
		}else{
			for (int i = 0; i < fileList.length; i++) {
				for (int j = 0; j < ErrorLogList.size(); j++) {
					if(!fileList[i].getName().equals(ErrorLogList.get(j).getNas_path())){
						newDirectory.add(fileList[i].getPath());
					}
				}
				fileList[i].getName();
			}
		}
		return newDirectory;
	}
	
	
	
	@Override
	public int  readAllFloderAndErrorLog(String path) {
		//FileUtil.login();
		try{
		 readAllFloderAndErrorLog(path,0,1);
		}catch(Exception e){
			System.out.println("读取错误日志出现问题");
		}
		return 0;
	}
	
	public int  readAllFloderAndErrorLog(String path,int id,int level){
		File file = new File(path);
		List<ErrorLog> ErrorLogList=new ArrayList<ErrorLog>();// 
		int number=readFile(ErrorLogList,file,id,level,id+"");
		int ErrorLogNo=0;
		for (ErrorLog ErrorLog : ErrorLogList) {
			save(ErrorLog);
			if(ErrorLog.getIsfile()!=null&&ErrorLog.getIsfile().equals("true")){
				ErrorLogNo++;
			}
		}
		return ErrorLogNo;
	}
	public int  readFile(List<ErrorLog> ErrorLogList,File directory,Integer pid,Integer level,String idPath) {
		File[] fileList = listFilesFilter(directory);
		//ErrorLogList
		level=level+1;		
		Integer id=pid+1;
		for (int i = 0; i < fileList.length; i++) {
			id=id+i;
			String next_id_path=idPath+","+id;
			String name=fileList[i].getName();
			String state="open";
			 
			ErrorLog ErrorLog=new ErrorLog(id.toString(), pid.toString(), name, level.toString(), next_id_path+",", state, DateUtil.getSystemDate());

			if (fileList[i].isDirectory()) {
				 
					ErrorLogList.add(ErrorLog);
					id=readFile(ErrorLogList,fileList[i],id,level,next_id_path);
			}else if (fileList[i].isFile()) {
			      String fileName=name;
				String file_create_time=DateUtil.getDateStringByformat("yyyy-MM-dd",fileList[i].lastModified());
				ErrorLog.setFile_create_time(file_create_time);
				//ErrorLog.setIsroot("true");
				ErrorLog.setIsfile("true");
				ErrorLog.setNas_path(fileList[i].getPath());
				String local_name=file_create_time+"_"+ErrorLog.getOname();
				ErrorLog.setLocal_name(local_name);
				ErrorLog.setLocal_path(Parameter.LOCAL_PATH+"\\"+local_name);
				FileUtil.copyfileChannel(ErrorLog.getNas_path(), Parameter.LOCAL_PATH+"\\"+local_name);
				ErrorLogList.add(ErrorLog);
			}
			
		}
		return id;
		
	}

	 
	
	
	 
	
	  /**
	   * 过滤 并按照时间排序，时间越早越靠前
	   * @param file
	   * @return
	   */
	 public File[] listFilesFilter(File file) {
		 List<File> fileList=new LinkedList<File>();
		 File[] fileArray=file.listFiles();
		 for (int i = 0; i < fileArray.length; i++) {
			if (fileArray[i].isDirectory()) {
				fileList.add(fileArray[i]);
				continue;
			}
			String fileName = fileArray[i].getName();
			if(fileName.length()<7) continue;
			String prefix = fileName.substring(fileName.lastIndexOf(".") - 3);
			if (prefix.toLowerCase().equals("err."+Parameter.FILE_TYPE_TXT)) {
				fileList.add(fileArray[i]);
			}

		}
		return fileList.toArray(new File[fileList.size()]);
    }





}
